/**
 * 上传相关API
 * 处理文件上传和OCR识别
 */

import apiClient from './api.js';

/**
 * 上传图片并进行OCR识别
 * @param {File} imageFile - 图片文件
 * @returns {Promise<Object>} OCR识别结果 { success, data: { text, confidence, ... }, message }
 */
export const uploadAndRecognize = async (imageFile) => {
  try {
    // 创建FormData
    const formData = new FormData();
    formData.append('image', imageFile);
    
    // 调用API（使用统一的apiClient，会自动添加baseURL和token）
    const response = await apiClient.post('/upload/ocr', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      timeout: 45000, // OCR可能需要较长时间
    });
    
    return response.data;
  } catch (error) {
    // 统一错误处理
    throw {
      success: false,
      message: error.response?.data?.message || error.message || 'OCR识别失败',
      type: error.response?.data?.type || 'OCR_ERROR',
      status: error.response?.status,
      code: error.code,
    };
  }
};

/**
 * 批量上传图片并进行OCR识别
 * @param {File[]} imageFiles - 图片文件数组
 * @returns {Promise<Object>} OCR识别结果
 */
export const uploadAndRecognizeMultiple = async (imageFiles) => {
  try {
    const formData = new FormData();
    imageFiles.forEach((file) => {
      formData.append('images', file);
    });
    
    const response = await apiClient.post('/upload/ocr/batch', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      timeout: 90000, // 批量OCR需要更长时间
    });
    
    return response.data;
  } catch (error) {
    throw {
      success: false,
      message: error.response?.data?.message || error.message || '批量OCR识别失败',
      type: error.response?.data?.type || 'BATCH_OCR_ERROR',
      status: error.response?.status,
      code: error.code,
    };
  }
};

